﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

using Obsidian.Utils;
using Obsidian.Edm;
using Obsidian.Data.Sql;
using Obsidian.Data.Sql.SqlSrvClient;
using Oak.Core.Data;
using Oak.Model;

namespace Oak.Core.Data
{
    public class SessionDA
    {

        internal CoSessionInfo SelectSessionByKey(string sessionKey, DateTime time)
        {
            string sqlText = SqlTextLoader.Get("Oak.Core.Data.SessionDA.SelectSessionByKey");
            sqlText = sqlText.Replace("$NOW$", time.ToString("yyyy-MM-dd hh:mm:ss"));
            sqlText = sqlText.Replace("$IN_SESSION_KEY$", sessionKey);
            CoSessionInfo s = new CoSessionInfo();
            SqlSrvExecutor exr = new SqlSrvExecutor(s.GetDataBase().ConnectionString);
            DataReader dr = new DataReader(exr.ExecuteReader(sqlText));
            if (dr.Read())
            {
                s.SessionKey.Set(dr.GetString(s.SessionKey.GetDbField().Name));
                s.LoginTime.Set(dr.GetDateTime(s.LoginTime.GetDbField().Name));
                s.Data.Set(dr.GetString(s.Data.GetDbField().Name));
                s.Expires.Set(dr.GetInt32(s.Expires.GetDbField().Name));
                s.AccessTime.Set(dr.GetDateTime(s.AccessTime.GetDbField().Name));
                s.ExpiresTime.Set(dr.GetDateTime(s.ExpiresTime.GetDbField().Name));
                dr.Close();
                return s;
            }
            else
            {
                dr.Close();
                return null;
            }
        }

        internal int DeleteSessionByKey(string sessionKey)
        {
            CoSessionInfo s = new CoSessionInfo();
            IDbHandler dbh = s.CreateHandler();
            dbh.Where(s.SessionKey.Equals(sessionKey));
            return dbh.Delete();
        }

    }
}
